package com.lingnan.wanxiangxinxun.controller.user;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lingnan.wanxiangxinxun.constant.redisConstant;
import com.lingnan.wanxiangxinxun.entity.dto.News_addDTO;
import com.lingnan.wanxiangxinxun.entity.dto.News_service_updateDTO;
import com.lingnan.wanxiangxinxun.entity.dto.query.News_queryDTO;
import com.lingnan.wanxiangxinxun.entity.po.News;
import com.lingnan.wanxiangxinxun.entity.po.User;
import com.lingnan.wanxiangxinxun.entity.vo.common.PageVO;
import com.lingnan.wanxiangxinxun.entity.vo.common.Result;
import com.lingnan.wanxiangxinxun.entity.vo.service.NewsVO;
import com.lingnan.wanxiangxinxun.service.INewsService;
import com.lingnan.wanxiangxinxun.service.IUserService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


@RestController("UserNewsController")
@RequestMapping("/user/news")
public class NewsController {

    @Autowired
    private INewsService iNewsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate; // 存对象的时候用
    @Autowired
    private RedisTemplate<String, String> redisTemplate_String; // 存普通数字或者字符串的时候用


    //新增
    @PostMapping("/add")
    public Result addNews(@RequestBody @Valid News_addDTO newsAddDTO) {
        News news = new News();
        BeanUtils.copyProperties(newsAddDTO, news);
        news.setCreateTime(LocalDateTime.now());
        try {
            //1、保存新闻
            iNewsService.save(news);
            //2、更新作者作品数量
            UpdateWrapper<User> uw = new UpdateWrapper<>();
            uw.eq("id", news.getAuthorId()).setSql("works_num = works_num + 1");
            userService.update(uw);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增失败");
        }
        return Result.success();
    }


    //删除(单删)
    @DeleteMapping("/delete/{id}")
    public Result deleteOneNews(@PathVariable Integer id) {
        News n = iNewsService.getById(id);
        //1、删除新闻
        boolean res = iNewsService.deleteById(id);
        if (!res) {
            return Result.error("删除失败");
        }
        //2、更新作者作品数量
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.eq("id", n.getAuthorId()).setSql("works_num = works_num - 1");
        return Result.success();
    }

    //删除浏览历史
    @DeleteMapping("/deleteHistory/{ids}")
    public Result deleteHistory(@PathVariable List<Integer> ids, @RequestParam Integer userId) {
        for (Integer id : ids) {
            redisTemplate_String.opsForZSet().remove(redisConstant.USER_HISTORY_NEWS_KEY + userId, String.valueOf(id));
        }
        return Result.success();
    }


    //个人作品修改
    @PutMapping("/update")
    public Result updateNews(@RequestBody News_service_updateDTO newsDTO) {
        int res = iNewsService.updateOneNewsById(newsDTO);

        if (res == 0) { return Result.error("修改失败"); }
        if (res != 1){ return Result.error("修改发生错误"); }

        return Result.success();
    }


    //修改某条新闻的点赞
    @PutMapping("/updateLikeNum")
    public Result updateLikeNum(@RequestParam Integer newsId, @RequestParam Integer userId) {
        iNewsService.updateNewData_likeNum(newsId, userId);
        return Result.success();
    }

    //修改某条新闻的收藏
    @PutMapping("/updateFavoriteNum")
    public Result updateFavoriteNum(@RequestParam Integer newsId, @RequestParam Integer userId) {
        iNewsService.updateNewData_favoriteNum(newsId, userId);
        return Result.success();
    }

    //修改某条新闻的浏览量
    @PutMapping("/updateViewNum")
    public Result updateViewNum(@RequestParam Integer newsId, Integer userId) {
        iNewsService.updateNewData_viewNum(newsId, userId);
        return Result.success();
    }


    //查找--根据条件查InCondition
    @PostMapping("/getAllInCondition")
    public Result getNewsInCondition(@RequestBody News_queryDTO newsDTO) {
        PageVO<NewsVO> allInCondition = iNewsService.getInCondition(newsDTO);
        return Result.success(allInCondition);
    }

    //查找--获取热门新闻
    @GetMapping("/getHotNews")
    public Result pushHotNews() {
        List<News> hotNews = iNewsService.getHotNews(null);
        return Result.success(hotNews);
    }

    //查找--按照用户喜好推送新闻,按照最近20条点赞的新闻作为参考
    @GetMapping("/pushNews")
    public Result pushNews(Integer userId,
                            @RequestParam(defaultValue = "1") long current,
                            @RequestParam(defaultValue = "10") long size) {

        //推送一条头条新闻（从redis里面拿）
        String headlineId = redisTemplate_String.opsForValue().get(redisConstant.HEADLINE_NEWS_KEY);
        News headline;
        if(headlineId != null){
            headline = iNewsService.getById(headlineId);
        }else {
            headline = null;
        }

        List<News> newsByUserLike = iNewsService.pushNews(userId, current, size);
        if (headlineId != null) {
            newsByUserLike.add(0, headline);
        }
        return Result.success(newsByUserLike);
    }

    //查找--根据id查
    @GetMapping("/getById")
    public Result getNewsById(@RequestParam List<Integer> ids, Integer userId) {
        List<News> newsList = iNewsService.getNewsListById(ids, userId);
        return Result.success(newsList);
    }

    //查找--查找某用户点赞过的新闻
    @GetMapping("/getNewsByUserLike")
    public Result getNewsByUserLike(@RequestParam Integer userId,
                                    @RequestParam(defaultValue = "1") long current,
                                    @RequestParam(defaultValue = "20") long size){
        List<News> newsList = iNewsService.getNewsByUserLike(userId, current, size);
        return Result.success(newsList);
    }

    //查找--查找某用户收藏过的新闻
    @GetMapping("/getNewsByUserFavorite")
    public Result getNewsByUserFavorite(@RequestParam Integer userId,
                                        @RequestParam(defaultValue = "1") long current,
                                        @RequestParam(defaultValue = "20") long size){
        List<News> newsList = iNewsService.getNewsByUserFavorite(userId, current, size);
        return Result.success(newsList);
    }

    //查找--查找某用户的历史浏览
    @GetMapping("/getNewsByUserHistory")
    public Result getNewsByUserHistory(@RequestParam Integer userId,
                                       @RequestParam(defaultValue = "1") long current,
                                       @RequestParam(defaultValue = "20") long size){
        List<News> newsList = iNewsService.getNewsByUserHistory(userId, current, size);
        return Result.success(newsList);
    }

    //查找--相关阅读
    @GetMapping("/getNewsByRelated")
    public Result getNewsByRelated(@RequestParam Integer categoryId, @RequestParam Integer currentNewsId) {
        List<News> newsList = iNewsService.getRelatedNews(categoryId, currentNewsId);
        return Result.success(newsList);
    }

    //查找--热搜榜数据
    @GetMapping("/getHotSearchList")
    public Result getHotSearchList() {
        List<String> hotSearchList = iNewsService.getHotSearchList();
        return Result.success(hotSearchList);
    }

}
